<?php

namespace addons\wxfollowlogin\controller;

use addons\wxfollowlogin\model\WxfollowloginScene;
use addons\wxfollowlogin\library\Service;
use addons\wxfollowlogin\library\Wechat;
use think\addons\Controller;

class Api extends Controller
{

    public function index()
    {
        $config = get_addon_config('wxfollowlogin');

        $options = array(
            'token'          => $config['token'], //填写你设定的key
            'encodingaeskey' => $config['encodingaeskey'], //填写加密用的EncodingAESKey
            'appid'          => $config['appid'], //填写高级调用功能的app id
            'appsecret'      => $config['appsecret'] //填写高级调用功能的密钥
        );
        $weObj = new Wechat($options);
        $weObj->valid();
        $type = $weObj->getRev()->getRevType();
        switch ($type) {
            case Wechat::MSGTYPE_TEXT:
                $content = trim($weObj->getRev()->getRevContent(),"");

                $scene = WxfollowloginScene::get(['openid'=>'','scene_id'=>$content,'createtime'=>['gt',time()-60]]);

                if($scene){
                    $openid =  $weObj->getRev()->getRevFrom(); //openid
                    $userInfo = $weObj->getUserInfo($openid);

                    $headimgurl = empty($userInfo['headimgurl'])?'':$userInfo['headimgurl'];
                    $nickname = empty($userInfo['nickname'])?'':$userInfo['nickname'];

                    WxfollowloginScene::update(array('openid'=>$openid,'login_time'=>time()),['id'=>$scene->id]);
                    Service::connect(array('openid'=>$openid,'avatar'=>$headimgurl,'nickname'=>$nickname));
                    $weObj->text("恭喜您，登录成功")->reply();
                }
                break;
            case Wechat::MSGTYPE_EVENT:
                $eventArr = $weObj->getRev()->getRevEvent();
                if (!empty($eventArr['key'])) {
                    $eventKey = $eventArr['key'];
                    $scene_id = str_replace("qrscene_", "", $eventKey);
                    $openid = $weObj->getRev()->getRevFrom(); //openid
                    $userInfo = $weObj->getUserInfo($openid);

                    WxfollowloginScene::update(array('openid' => $openid, 'login_time' => time()), ['id' => $scene_id]);
                    Service::connect(array('openid' => $openid, 'avatar' => $userInfo['headimgurl'], 'nickname' => $userInfo['nickname']));
                    $weObj->text("恭喜您，登录成功")->reply();
                }
                break;
            case Wechat::MSGTYPE_IMAGE:
                break;
            default:

        }

    }

}
